package com.atguigu.day07;

import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

public class Flink08_State_Operator {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.分别获取两条流
        DataStreamSource<String> localStream = env.socketTextStream("localhost", 9999);
        DataStreamSource<String> hadoopStream = env.socketTextStream("hadoop102", 9999);

        //3.定义MapState
        MapStateDescriptor<String, String> mapStateDescriptor = new MapStateDescriptor<>("map-state", String.class, String.class);

        //4.广播流
        BroadcastStream<String> broadcastStream = localStream.broadcast(mapStateDescriptor);

        //5.链接广播流以及普通流
        BroadcastConnectedStream<String, String> connectedStream = hadoopStream.connect(broadcastStream);

        //6.通过本地的数据控制hadoop流中的逻辑
        SingleOutputStreamOperator<String> result = connectedStream.process(new BroadcastProcessFunction<String, String, String>() {
            @Override
            public void processElement(String value, ReadOnlyContext ctx, Collector<String> out) throws Exception {
                //获取广播状态并取出数据
                ReadOnlyBroadcastState<String, String> broadcastState = ctx.getBroadcastState(mapStateDescriptor);

                String swith = broadcastState.get("switch");

                if ("1".equals(swith)) {
                    out.collect("执行加法逻辑");
                } else if ("2".equals(swith)) {
                    out.collect("执行乘法逻辑");
                } else {
                    out.collect("执行其他逻辑");
                }


            }

            @Override
            public void processBroadcastElement(String value, Context ctx, Collector<String> out) throws Exception {
                //提取广播状态，并将数据放入状态中
                BroadcastState<String, String> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
                broadcastState.put("switch", value);

            }
        });
        result.print();

        env.execute();

    }
}
